var pcsWatermark = angular.module('pcsWatermark', []);

pcsWatermark.controller('watermarkCtrl', function ($rootScope, $scope, $http) {
	$rootScope.userInfo = {"token":""};
	$rootScope.userInfo.token = access_token;
	
	$scope.document = {"id":""};
	
	$scope.watermarkContent = "this is watermark test watermarkContent is 'www.foxitcloud.com' ";
  
    var DocumentLoader = function() { 
        function _doPrepare(baseUrl, requestData){
            var deferred = $.Deferred();
            var url = baseUrl + "prepare";       

            $.ajax({
                'url' : url,
                'dataType' : 'json',
                'contentType' : "application/x-www-form-urlencoded",
                'data': requestData
            })
            .success(function(data, textStatus, xhr) {               
                if (data.code == 0 && 
                    data.status ==  0){                   
                    deferred.resolve(data);

                }
                else{
                    deferred.reject(data);
                }
            })
           .error(function(xhr, response, errorThrown) {
                WebPDF.logger("error", {
                    "url": url,
                    "data": requestData,
                    "message": response
                });

                deferred.reject();
           });
           return deferred.promise();
        }

        function _getJobStatusOnce(baseUrl, requestData){
            var deferred = $.Deferred();
            var url = baseUrl + "jobStatus";
            $.ajax({
                'url' : url,
                'dataType':'json',
                'contentType':"application/x-www-form-urlencoded",
                'data': requestData
            })
            .success(function(data, textStatus, xhr){    
                if (data.code === 0 && 
                    data.status == 0) {         
                    deferred.resolve(data);
                }
                else{
                    deferred.reject(data);
                }
            })
            .error(function(response){
                WebPDF.logger("error", {
                    "url": url,
                    "data": requestData,
                    "message": response
                });            
                deferred.reject();
            });

            return deferred.promise();
        }

        function _getJobStatus(baseUrl, requestData,retryCount){
            var deferred = $.Deferred();
            _getJobStatusOnce(baseUrl, requestData)
            .done(function(data){
                deferred.resolve(data);
            })
            .fail(function(data){
                //继续读取状态               
                if (data && data.code === 0){
                    (function(_baseUrl, requestData,  _retryCount,  _deferred) {
                        if (_retryCount <= 0 ){
                            _deferred.reject();
                        }  
                        else{                         
                            setTimeout(function() {
                                _getJobStatus(_baseUrl, requestData, _retryCount)
                                .done(function(data){
                                    _deferred.resolve(data);
                                })
                                .fail(function(reason) {
                                    _deferred.reject(reason);
                                })
                                .progress(function(data){
                                    _deferred.notify(data);
                                });
                            }, 2000);
                        }
                    })(baseUrl, requestData, retryCount - 1, deferred);

                    deferred.notify(data);
                }
                //请求异常
                else{
                    deferred.reject(data);
                }
            });
           
            return deferred.promise();
        }

        function _canGetManifest(baseUrl, requestData, option){
            var deferred = $.Deferred();
            var retryCount = option.maxRetryCount;
            _doPrepare(baseUrl, requestData)
            .done(function(data){              
                deferred.resolve(data);
            }) 
            .fail(function(data){               
                if (data && 
                    data.code == 0){
                    _getJobStatus(baseUrl, requestData, retryCount)
                    .done(function(data){  
                        deferred.resolve(data);                      
                    })
                    .fail(function(data){
                        deferred.reject(data);
                    })
                    .progress(function(data){                       
                        deferred.notify(data);
                    });
                }
                //请求异常
                else{
                    deferred.reject(data);
                }
            });

            return deferred.promise();

        }
        function _doGetManifest(baseUrl,requestData){
            var deferred = $.Deferred();
            var url = baseUrl + "manifest";
            $.ajax({
                'url': url,
                'dataType': 'json',
                'contentType':"application/x-www-form-urlencoded",
                'data': requestData
            })
            .success(function(response, textStatus, xhr){
                if(response.status == 0 && 
                    response.code == 0 ){                
                    deferred.resolve(response.data);
                }
                else{                   
                    deferred.reject(response);
                }
             })
            .error(function(xhr, response, errorThrown){
               WebPDF.logger("error", {
                    "url": url,
                    "data": requestData,
                    "message": response
                });
                deferred.reject();
            });

            return deferred.promise();
        }

        /**
         * Load document asynchronize
         * @param {WebPDF.ReaderApp} app instance.
         * @param {String} password of PDF document.
         * @param {Boolean | null} isCheckPassword Whether the request is for checking password or parsing document.
         * @param {Boolean | null} isCheckStatus.
         * @param {Function} doneHandler callback for load document successfully.
         * @param {Function} failedHandler callback for load document failed.
         * @private
         * @constructor
         */
        this.asyncLoadDocument = function(option, pdfPassword){           
            var deferred = $.Deferred();
            var baseUrl = option.url;
            var requestData = {
                's3Key' : option.fileId
            };

            if (pdfPassword) {
                requestData.psd = pdfPassword;
            }

            _canGetManifest(baseUrl, requestData, option)
            .done(function(data){
                _doGetManifest(baseUrl, requestData)
                .done(function(data){
                    deferred.resolve(data);
                })
                .fail(function(data){
                    deferred.reject(data);
                });                
            })
            .fail(function(data) {
                 deferred.reject(data);
            })
            .progress(function(data) {               
                deferred.notify(data);
            }); 


            return deferred.promise();
        };      
    };   


    var ImgLoadService = function() {
        function _loadImagOnce (url) {             
            var deferred = $.Deferred();
            $.ajax({
                    url: url,                  
                    dataType: "text",                    
                    contentType: "application/x-www-form-urlencoded",
                })
                .success(function(data, textStatus, xhr) {
                    if (data.length === 1){
                         deferred.reject("inprogress");
                    }
                    else{
                        deferred.resolve(data); 
                    }
                })
                .error(function(xhr, response, errorThrown) {
                    WebPDF.logger("error", {
                        "url": url,                      
                        "message": response
                    });
                    deferred.reject("error");                                       
                });
            return deferred.promise();
        }        

        function _loadImg(url, retryCount){
            var deferred = $.Deferred();          

            _loadImagOnce(url)
                .done(function(data) {
                    deferred.resolve(data);
                })
                .fail(function(reason) {
                    if (reason === 'inprogress'){
                        (function(_url, _retryCount,  _deferred) {
                            if (_retryCount <= 0 ){
                                _deferred.reject("retryOut");
                            }  
                            else{                         
                                setTimeout(function() {
                                    _loadImg(_url, _retryCount).done(function(data){
                                        _deferred.resolve(data);
                                    }).fail(function(reason) {
                                        _deferred.reject(reason);
                                    });
                                }, 2000);
                            }
                        })(url, retryCount - 1, deferred);
                    }
                    else{
                        deferred.reject("error");
                    }
            });           
            return deferred.promise();
        }
        this.loadImg = _loadImg;        
    };
	/*
	 * add search index
	 */
	$scope.watermark = function() {
//		alert($scope.document.id);
		if($scope.document.id == ""){
			noty({text:"please change a file!", type: 'warning',layout:'center'});
			return;
		};
		
		$http.get('/rest/documents/' + $scope.document.id + "?access_token=" + $rootScope.userInfo.token).then(function(response) {
								
			var s3Key = {"key": response.data.data.doc_url};
			var watermarkContent = $("#id").val();
            if (watermarkContent){
                 s3Key.watermarkContent = watermarkContent;
            }       
			var documentLoader = new DocumentLoader();
			var option = {
				url: '/rest/webpdf/', 
				fileId: encodeURIComponent(JSON.stringify(s3Key)),
				maxRetryCount: 50
			};
			documentLoader.asyncLoadDocument(option, '').done(function(data){
				var type = data.doctype == 2 ? true : false;
               

                var imgUrl = '/rest/webpdf/image/0/100?form='+type+'&&s3Key=' + encodeURIComponent(JSON.stringify(s3Key));

                var imgLoadService = new ImgLoadService();
                imgLoadService.loadImg(imgUrl, 10).done(function() {
                    $("#background").attr("src", imgUrl);
                });			

				//documentLoader.loadImage('/rest/webpdf/image/0/100?s3Key=' + encodeURIComponent(JSON.stringify(s3Key));
			})					
		}
		)		
	}


});